package com.juku2024.juku

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.adapter.NoteExportAdapter
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.db.entity.NoteExportEntity
import com.juku2024.juku.dialog.CommonDialog
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.RxUtils
import com.juku2024.juku.tools.WrapLinearLayoutManager
import com.juku2024.juku.widget.LoadingView
import java.io.File

class NoteExportActivity: AppCompatActivity() {

    private lateinit var btnBack: View
    private lateinit var loadingView: LoadingView
    private lateinit var recyclerView: RecyclerView
    private val noteAdapter by lazy { NoteExportAdapter(ArrayList()) }
    private var shareDialog: CommonDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_note_export)
        btnBack = findViewById(R.id.btnBack)
        loadingView = findViewById(R.id.export_loadingView)
        recyclerView = findViewById(R.id.recycler_export)

        recyclerView.layoutManager = WrapLinearLayoutManager(this)
        recyclerView.adapter = noteAdapter
        doGetAllNodes()

        noteAdapter.setOnItemClickListener { _, _, position ->
            val item = noteAdapter.getItem(position)
            if (TextUtils.isEmpty(item.path)) return@setOnItemClickListener
            val file = File(item.path!!)
            AppUtils.shareFile(this, file)
        }
    }

    private fun doGetAllNodes() {
        loadingView.showLoading()
        RxUtils.doObservable<ArrayList<NoteExportEntity>>({
            val list = NoteRoomUtils.getInstance().noteExportDao().queryAll()
            if (list.isNullOrEmpty()) {
                it.onNext(ArrayList<NoteExportEntity>())
            } else {
                it.onNext(list as ArrayList<NoteExportEntity>)
            }
        }, {
            if (isFinishing || isDestroyed) return@doObservable
            loadingView.hideLoading()
            if (it.isNullOrEmpty()) {
                loadingView.showEmptyStatus("您还未创建笔记！")
                return@doObservable
            }
            noteAdapter.setList(it)
        })
    }
}